const {
	Service
} = require('uni-cloud-router')

module.exports = class MockService extends Service {
	constructor(arg) {
		super(...arguments)
		const {
			ctx
		} = this
		this.$uniid = ctx.$id
	}
	async login(data) {
		const {
			ctx
		} = this
		let params = ctx.event.data
		console.log(ctx.context);
		let res = await this.$uniid.login(params);
		await this._login_log(ctx.context, res);
		return res
	}
	async register(data) {
		const {
			ctx
		} = this
		let params = ctx.event.data
		let res = await this.$uniid.register(params);
		return res
	}

	async logout(data) {
		const {
			ctx
		} = this
		let token = ctx.event.token
		let res = await this.$uniid.logout(token);
		return res
	}
	async token(data) {
		const {
			ctx
		} = this
		let res = await ctx.$id.checkToken(ctx.event.token);
		return res
	}
	async userinfo(data) {
		return {
			code: 0,
			message: '获取用户信息成功',
			...this.ctx.$userinfo
		}
	}
	// 登录记录
	async _login_log(context, res = {}, type = 'login') {
		const {
			ctx
		} = this
		const db = ctx.db
		const now = Date.now()
		const uniIdLogCollection = db.collection('uni-id-log')
		let logData = {
			appid: context.APPID || '',
			deviceId: context.DEVICEID || '',
			ip: context.CLIENTIP || '',
			type,
			ua: context.CLIENTUA,
			create_date: now
		};

		Object.assign(logData,
			res.code === 0 ? {
				user_id: res.uid,
				state: 1
			} : {
				state: 0
			})

		return uniIdLogCollection.add(logData)
	}
}
